package com.example.wj.controller;

import com.example.wj.pojo.Book;
import com.example.wj.service.UserService;
import com.example.wj.pojo.Result;
import com.example.wj.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    String un;
    String cover;
    User user1;
    @Autowired
    UserService userService;
    /*
    *
    * 登录功能，并通过用户名存储一个user对象user1
    * */
    @CrossOrigin
    @RequestMapping(value = "api/login")
    @ResponseBody
    public Result login(@RequestBody User user, HttpSession session){
        String username= user.getUsername();
        System.out.println(username);
        username= HtmlUtils.htmlEscape(username);
        String password=user.getPassword();

        System.out.println(password);
        User dengluuser = userService.getUser(username, password);
        System.out.println("user1="+dengluuser);
        user1 = userService.seachUser(username);
        System.out.println(user1);
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
       if("".equals(username) && "".equals(password)){
           return new Result(403);
       }else if("".equals(password)){
           return new Result(402);
       }else if("".equals(username)){
           return new Result(401);
       }else{
           {

                 try{
                     subject.login(usernamePasswordToken);
                     session.setAttribute("user1",user1);
                     System.out.println("session域内容"+session.getAttribute("user1"));
                     if("管理员".equals(user1.getName())){
                         return new Result(201);
                     }else{
                         return new Result(200);
                     }


                 }catch (Exception e){
                     System.out.println(e);
                     System.out.println("登录失败");
                     return new Result(400);

                 }





           }
       }



    }
    /*
    *
    * 默认是用登录时创建对象得用户名，当执行了getusernamebyid会替换成对应id得用户名
    *
    * */
    @GetMapping ("api/getusername")
    @ResponseBody
    public String setusername(){
         un = user1.getUsername();
       if(getusernamebyid(user1.getId())!=null){
           un=getusernamebyid(user1.getId());
       }
        return un;
    }
    /*
    * 默认是用登录时创建对象得头像，当执行了getusercoverbyid会替换成对应id得头像
    *
    * */
    @GetMapping ("api/getcover")
    @ResponseBody
    public String setusercover(){

        cover=user1.getCover();
        if(getusercoverbyid(user1.getId())!=null){
            cover=getusercoverbyid(user1.getId());
            System.out.println("/getcover"+cover);
        }

        return cover;
    }
/*
*
* 验证旧密码是否相同
* */
//@CrossOrigin
//@RequestMapping("api/confirmuser")
//
//    @ResponseBody
//    public Result confirmuser(@RequestBody User user){
//        User user1 = userService.seachUser(user.getUsername());
//
//        Result result = new Result();
//        String password=user.getPassword();
//    System.out.println("旧密码"+password);
//        if(password.equals(user1.getPassword())){
//
//            result.setCode(200);
//            System.out.println(result);
//        }
//        return result;
//    }

    /**
     *
     * @param user
     * @return Result
     * 作用：更改密码
     */
    @RequestMapping("api/repassword")
@ResponseBody
    public Result repassword(@RequestBody User user){
        User user1 = userService.seachUser(user.getUsername());
        System.out.println("修改密码的用户"+user1);
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        //生成简单hash码
        String encodedPassword = new SimpleHash("md5", user.getPassword(), salt, 2).toString();
        user1.setSalt(salt);
        user1.setPassword(encodedPassword);
        System.out.println("新密码" + salt + encodedPassword);
        //得到hash密码

        int save = userService.save(user1);







    System.out.println("修改密码成功");
    return new Result(200);

}

    /**
     * 作用：更改用户名存入到
     * @param newusername
     * @param id
     * @return Result
     */
    @RequestMapping("api/reusername")
    @ResponseBody
    public Result reusername(@RequestParam(value = "newusername") String newusername,@RequestParam(value = "id") Integer id){
        User user = userService.findUserById(id);

        user.setUsername(newusername);
        int save = userService.save(user);
        Result result=new Result();
        if(save==1){
            result.setCode(200);
            System.out.println("修改名字成功");
        }else {
            System.out.println("修改名字失败");
        }
return result;
    }
/*
* 作用：把用户输入得链接存入数据库中
*
* */
    @RequestMapping("api/reusercover")
    @ResponseBody
    public Result reusercover(@RequestParam(value = "newcover") String newcover,@RequestParam(value = "id") Integer id){
        User user = userService.findUserById(id);

        user.setCover(newcover);
        int save = userService.save(user);
        Result result=new Result();
        if(save==1){
            result.setCode(200);
            System.out.println("修改头像成功");
        }else {
            System.out.println("修改头像失败");
        }
        return result;
    }

    /**
     * 作用：拿到登录时得用户id
     * @return
     */
    @RequestMapping("api/getid")
    @ResponseBody
    public Integer getid(){
        Integer id = user1.getId();
        System.out.println(id);
        return id;
    }

    /**
     * 通过用户id重新拿到名字，用于更新用户名
     * @param id
     * @return
     */
    @RequestMapping("api/getusernamebyid")
    @ResponseBody
    public String getusernamebyid(@RequestParam(value = "id") Integer id){
        User userById = userService.findUserById(id);
        String username = userById.getUsername();
        return username;
    }

    /**
     * 通过用户id重新拿到头像，用户更新用户头像
     * @param id
     * @return
     */
    @RequestMapping("api/getusercoverbyid")
    @ResponseBody
    public String getusercoverbyid(@RequestParam(value = "id") Integer id){
        User userById = userService.findUserById(id);
        String usercover = userById.getCover();
        return usercover;
    }

//    @RequestMapping(value = "api/appindex/{name}")
//    @ResponseBody
//    public User seachUser(@PathVariable("name") String name){
//        User user = userService.seachUser(name);
//        System.out.println(user);
//        return user ;
//    }

    /**
     * 作用：用于把前端得头像链接存到数据库中
     * @param cover
     * @param request
     * @return
     */
    @PostMapping("api/setcover")

    public Result setcover(@RequestParam(value = "file") MultipartFile cover, HttpServletRequest request){
        System.out.println(cover);
        String filename = cover.getOriginalFilename();
        System.out.println("33333");
        String upload = request.getServletContext().getRealPath("setcover/");
        String path = upload + filename;
        System.out.println(path);
        System.out.println("user1"+user1);

            user1.setCover(path);
            userService.save(user1);
           return new Result(200);




    }
    @RequestMapping("api/logout")
    @ResponseBody
    public Result logout(HttpSession session){
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        System.out.println("用户已退出");
        System.out.println("session域内容"+session.getAttribute("user"));
        return new Result(200);
    }
    @RequestMapping("api/authentication")
    @ResponseBody
    public String authentication(){
        return "身份登录验证成功";
    }

/*
* 注销账号
* */
    @RequestMapping("api/destory")
    @ResponseBody
    @Transactional
    public  void destory(@RequestParam(value = "username") String username){

       userService.delete(username);
    }

    /*
    * 图书购买功能
    * */
    @RequestMapping("api/buy")
    @ResponseBody
    public Result buy(@RequestParam(value = "book") String book){
        String books1;

        String books = user1.getBooks();
        System.out.println("books="+books);
        if(null==books){
            books1=book;
        }else {
            books1=books+","+book;
        }


        user1.setBooks(books1);
        userService.save(user1);
        System.out.println("user1="+user1);


    return new Result(200);
    }
    @RequestMapping("api/getbooks")
    @ResponseBody
    public String[] getbooks(){
        String books = user1.getBooks();

        String[] split = books.split(",");
        String[] books1=new String[split.length];
        for (int i = 0; i < split.length; i++) {
            books1[i]=split[i];
        }
        System.out.println("books1="+books1);
        return books1;
    }
    @RequestMapping("api/delorder")
    @ResponseBody
    public Result delOrder(@RequestParam(value = "delbook") String delbook){
           Result result;
        String books = user1.getBooks();
        String[] split = books.split(",");
        String[] newbooks=new String[split.length];
        String book1 = null;

        for (int i = 0; i < split.length; i++) {
            if(split[i].equals(delbook)){
                split[i]="";

            }
           if("".equals(split[i])){
               newbooks[i]=split[i];

           }else{
               newbooks[i]=split[i]+",";
           }

        }

        for (int i = 0; i < newbooks.length; i++) {
            book1+=newbooks[i];
        }
        System.out.println("362books="+book1);
        user1.setBooks(book1);
        userService.save(user1);
        result=new Result(200);
        return result;
    }
    @RequestMapping("api/order")
    @ResponseBody
    public List<User> findOrder(){
        List<User> all = userService.findAll();
        for(int i=0;i< all.size();i++  ){
            System.out.println(all.get(i));
        }
        return all;
    }
    @RequestMapping("api/order/delete")
@ResponseBody
    public Result orderDelete( @RequestParam(value = "id") int i){
        User userById = userService.findUserById(i);
        userById.setBooks(null);
        userService.save(userById);
        return new Result(200);

    }
    @RequestMapping("api/customer")
    @ResponseBody
    public List<User> findCustomer(){
        List<User> all = userService.findAll();
        for(int i=0;i< all.size();i++  ){
            System.out.println(all.get(i));
        }
        return all;
    }
}
